package cn.jy.careuplusdoctor.utils;

import java.util.Stack;

import cn.jy.careuplusdoctor.main.LoginActivity;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;

/**
 * 
 * @author lxy
 * @date 2015-01-09
 * @since 1.0
 */
public class AppManager
{
	private static Stack<Activity> activities;
	public AppManager()
	{
		activities = new Stack<Activity>();
	}
	
	public void addActivity(Activity activity)
	{
		activities.add(activity);
	}
	/**
	 * 结束最后入栈的activity
	 */
	public void finishActivity()
	{
		Activity activity = getTopActivity();
		finishActivity(activity);
	}
	
	/**
	 * 最后入栈的activity
	 */
	public Activity getTopActivity()
	{
		Activity activity = activities.lastElement();
		return activity;
	}
	/**
	 * 结束指定的activity
	 * @param activity
	 */
	public void finishActivity(Activity activity)
	{
		if (activity !=null)
		{
			activities.remove(activity);
			activity.finish();
			activity = null;
		}
	}
	
	//结束所有的activity
	public void finishAllActivity()
	{
		int count = activities.size();
		for (int i = 0; i < count; i++)
		{
			Activity activity = activities.get(i);
			finishActivity(activity);
		}
		activities.clear();
	}
	/**
	 * 退出程序
	 * @param context
	 */
	public void appExit(Context context)
	{
		finishAllActivity();
		
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		
		am.restartPackage(context.getPackageName());
		
		System.exit(0);
		
	}
	/**
	 * 重新登录
	 */
	public void logout(Activity activity)
	{
		Intent intent = new Intent();
		intent.setClass(activity, LoginActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		activity.startActivity(intent);
		activity.finish();
	}
}
